package com.pearl.nacos.config.demo.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.google.common.base.Preconditions;
import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.driver.jdbc.core.driver.ShardingSphereDriverURLProvider;
import java.nio.charset.StandardCharsets;

/**
 * @author TD
 * @version 1.0
 * @date 2024/4/25
 */
public class NacosCloudDriverURLProvider implements ShardingSphereDriverURLProvider {

    private static final String NACOS_TYPE = "nacos:";

    /**
     * url 包含了 nacos: 时
     * 表示使用当前类加载配置
     */
    @Override
    public boolean accept(String url) {
        return StringUtils.isNotBlank(url) && url.contains(NACOS_TYPE);
    }

    @Override
    public byte[] getContent(String url) {
        // 检查
        String dataId = StringUtils.substringAfter(url, NACOS_TYPE);
        Preconditions.checkArgument(StrUtil.isNotEmpty(dataId), "dataId 不能为空");

        NacosConfigManager nacosConfigManager = NacosConfigManagerUtils.getNacosConfigManager();
        Preconditions.checkArgument(ObjectUtil.isNotNull(nacosConfigManager), "NacosConfigManager 不能为 null");

        // 获取配置
        ConfigService configService = nacosConfigManager.getConfigService();
        NacosConfigProperties nacosConfigProperties = nacosConfigManager.getNacosConfigProperties();// Nacos 配置
        try {
            String content = configService.getConfig(dataId, nacosConfigProperties.getGroup(), nacosConfigProperties.getTimeout());
            System.out.println(content);
            return content.getBytes(StandardCharsets.UTF_8);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }
}
